<?php
session_start();
include 'inc/db_connect.php';
include 'inc/db_op.php';
include 'inc/html_op.php';
include 'inc/form_op.php';

date_default_timezone_set('PRC');

$delete_task_post_name = "delete_task_id";

$task_insert_fields = Array("initiator", "type_id", "product_id", "title", "ticket_id", "content", "priority", "project_id",
  "is_trip_out", "creator_user_id", "assignto", "progress", "scheduled_start_time","deadline");

$task_modify_fields = Array("title", "content", "product_id", "type_id", "priority",
  "is_trip_out", "project_id", "assignto", "progress", "scheduled_start_time","deadline");

$new_task_project_select_div_id = '"new_task_project_select"';
$user_id = $_SESSION["user_id"];
$task_form_rows = array(
  "类型"=>get_task_type_options(),
  "标题"=>"<input type=text name=title required size=40 />",
  "内容"=>"<textarea rows=12 cols=50 name=content required></textarea>",
  "计划开始时间"=>"<input type=date name=scheduled_start_time value='".date('Y-m-d')."'>",
  "完成期限"=>"<input type=date name=deadline value='".date('Y-m-d')."'>",
  "分配给"=>get_assignto_select($user_id).' <input type=checkbox name=mailassignment value=1 />发送邮件提醒',
  "重要等级"=>gen_select("priority",array("高"=>"高","中"=>"中","低"=>"低")),
  "出差"=>"<input type='checkbox' name='is_trip_out' value=1 />",
//  "来源"=>gen_select("initiator", array("自己"=>"自己","部门管理者"=>"部门管理者","分公司领导"=>"分公司领导"
//    ,"系统部"=>"系统部","营销"=>"营销","客户"=>"客户","其他"=>"其他")),
  "项目"=>"<input type=text name=project_name placeholder='请填写项目名称检索'".
      " onchange='get_project_select($new_task_project_select_div_id, this.value)' />".
      "<select id=$new_task_project_select_div_id name=project_id>".
      "<option value=-1>无选项</option></select>",
//  "产品"=>get_product_options(),
  "TicketID"=>"<input type=number name=ticket_id size=8>",
  ""=>"<button type=submit name=new_task_submit id=new_task_submit>提交</button>"
);

$task_form = "<h2>添加新任务</h2>
  <form name=new_task method=post>".
  "<input type='hidden' name=progress value=0 />".
  "<input type='hidden' name=creator_user_id value=$user_id />".
  "<input type='hidden' name=assignto value=$user_id />".
  gen_twincol_table("task_form", $task_form_rows).
  "</form>";

function get_wlog_list_of_task($task_id) {
  $sql = "select date_format(end_time, '%m-%d %a') end_time, user_info.name user_name, title, content, updated_progress ".
         " from work_log join user_info on work_log.user_id = user_info.id ".
         " where task_id = $task_id order by end_time desc";
  $rows = db_get($sql);
  $list_items=array();
  foreach($rows as $row) {
    $disp_str = $row['user_name'].' '.$row['end_time'].' '.$row['title']." 完成".$row['updated_progress'].'%';
	$list_items[$disp_str] = $row['content'];
  }
  return gen_list_with_tip($list_items, "ul");
}

function get_task_detail_div($task_id, $task_scheduled_time_str, $content) {
  $div_id = "div_task_$task_id";
  $show_detail_div_id = $div_id.'_show';
  $hide_detail_div_id = $div_id.'_hide';

  $wlog_list = get_wlog_list_of_task($task_id);
  $show_link = "<a href=javascript:hide_div('$show_detail_div_id');show_div('$hide_detail_div_id','inline')>展开</a>";
  $show_detail_div = "<div id='$show_detail_div_id' style='display:inline'>$show_link</div>";
  $hide_link = "<a href=javascript:hide_div('$hide_detail_div_id');show_div('$show_detail_div_id','inline')>收起</a>";
  $hide_detail_div = "<div id='$hide_detail_div_id' style='display:none'>$hide_link<p>$task_scheduled_time_str</p><p>$content</p>$wlog_list<p>$hide_link</p></div>";

  $html_str = $show_detail_div.$hide_detail_div;
  return $html_str;
}

function gen_task_table($where, $only_detail_link = 1, $order = '') {
  if ($order == '') {
    $order = 'priority, deadline';
  }

  $sql = "select task_info.id id, creator_user_id, convert(u2.name using gbk) c_name, priority, title, content, ticket_id, progress, scheduled_start_time, deadline, ";
  $sql .= " assignto, convert(user_info.name using gbk) name from task_info join user_info join user_info u2 on task_info.assignto = user_info.id ";
  $sql .= "and task_info.creator_user_id = u2.id";
  $sql .= " where $where ";
  $sql .= " order by ".$order;
  //$sql .= " order by priority, deadline $ristriction";
  //echo 'sql: '.$sql;
  $rows = db_get($sql);

  global $delete_task_post_name;

  $serialNo = 0;
  $tableId = '';
  $tableClass = '';
  $table_fields = array();
  $table_fields_width = array();
  $table_row = array();
  $table_rows = array();
  $prioritys = array('高'=>"<span class='hidden_str'>0</span>高", '中'=>"<span class='hidden_str'>1</span>中", '低'=>"<span class='hidden_str'>2</span>低");

  foreach($rows as $row) {
    $del_link = '';
  $modify_link = '';
  $wlog_link = '';
  if(0 == $only_detail_link) {
      $del_code = 'javascript:';
      $del_code .= 'confirm("真的要删除吗？")&&submit_a_value("'.$delete_task_post_name.'", "'.$row['id'].'")';
      $del_link = "<a href='".$del_code."'>删除</a>";
      $modify_code = 'javascript:get_task_modify_form("'.$row['id'].'", "task_modify_form", "todo_list");';
      $modify_code .= 'switch_disp("task_modify_form", "todo_list");';
      $modify_link = "<a href='".$modify_code."'>修改</a>";
      $wlog_code = 'javascript:submit_a_value("new_log_task_id", "'.$row['id'].'", "wlog.php");';
    $wlog_link = "<a href='".$wlog_code."'>添加工作记录</a>";
  }

  $title = $row['title'];
  $content = $row['content'];
  if(($row['progress']< 100) && (strtotime("today") > strtotime($row['deadline'])) ) {
    $title = "<b style='background:yellow'>".$title."</b>";
  }

  $time_start = strtotime($row['scheduled_start_time']);
  $time_end = strtotime($row['deadline']);
  $year = date('Y');
  $year_start = date('Y', $time_start);
  $year_end = date('Y', $time_end);
  $format_start_str = $year == $year_start ? 'm-d D' : 'Y-m-d D';
  $format_end_str = $year == $year_end ? 'm-d D' : 'Y-m-d D';
  $task_scheduled_time_str = '起止时间：'.date($format_start_str, $time_start).' ~ '.date($format_end_str, $time_end);
  $task_detail_div = get_task_detail_div($row['id'], $task_scheduled_time_str, $content.gen_ticket_link($row['ticket_id']));

  $creator_str = "";
  $assignto_str = "";

  if ($row['assignto'] == $_SESSION['user_id']) {
    // 待处理任务
    $creator_str = $row['c_name'];
    if ($tableId == '' || $tableClass == '') {
      $tableId = 'ToDoTable';
      $tableClass = 'sortable-onload-1-2 rowstyle-alt no-arrow';
    }
  } else if ($row['creator_user_id'] == $_SESSION['user_id']) {
    //已分配的任务
    $assignto_str = $row['name'];
    if ($tableId == '' || $tableClass == '') {
      $tableId = 'AssignedToDoTable';
      $tableClass = 'sortable-onload-1-2 rowstyle-alt no-arrow';
    }
  } else {
    // 部门其它未完成工作
    $creator_str = $row['c_name'];
    $assignto_str = $row['name'];
    if ($tableId == '' || $tableClass == '') {
      $tableId = 'DepartmentToDoTable';
      $tableClass = 'sortable-onload-1-2-3 rowstyle-alt no-arrow';
    }
  }

  if (count($table_fields) <= 0) {
    $table_fields['no'] = '序号';

    $table_fields['priority'] = '优先级';
    $table_fields_attr['priority'.'.class'] = 'sortable-text';
    $table_fields_attr['priority'.'_a.title'] = '按优先级排序';

    if ($assignto_str != '') {
      $table_fields['assignto'] = '实施人';
      $table_fields_attr['assignto'.'.class'] = 'sortable-text';
      $table_fields_attr['assignto'.'_a.title'] = '按实施人排序';
    }

    if ($creator_str != '') {
      $table_fields['creator_user_id'] = '分配人';
      $table_fields_attr['creator_user_id'.'.class'] = 'sortable-text';
      $table_fields_attr['creator_user_id'.'_a.title'] = '按分配人排序';
    }

    $table_fields['title'] = '任务描述';

    $table_fields['progress'] = '完成情况';
    $table_fields_attr['progress'.'.class'] = 'sortable-numeric';

    $table_fields['operate'] = '操作';
  }

    $table_row['no'] = ++$serialNo;
    $table_row['priority'] = $prioritys[$row['priority']] ? $prioritys[$row['priority']] : $row['priority'];
    if ($assignto_str != '') $table_row['assignto'] = $assignto_str;
    if ($creator_str != '') $table_row['creator_user_id'] = $creator_str;
    $table_row['title'] = $title.' '.$task_detail_div;
    $table_row['progress'] = $row['progress'].'%';
    $table_row['operate'] = $wlog_link.' '.$modify_link.' '.$del_link;

    array_push($table_rows, $table_row);
  }
  return gen_table_ext($table_fields, $table_rows, 1/*border*/, $tableId, $tableClass, $table_fields_attr);
}

function get_todo_list() {
  $head="<h2>待处理任务</h2>";
  $where = " progress < 100 and assignto = ".$_SESSION['user_id']." ";
  return $head.gen_task_table($where, 0);
}

function get_assigned_todo() {
  $head = "<h2>已分配的任务</h2>";
  $where = " progress < 100 and creator_user_id = ".$_SESSION['user_id']." and assignto != ".$_SESSION['user_id']." ";
  return $head.gen_task_table($where, 0);
}

function get_department_todo() {
  if(isset($_SESSION['user_id']) && is_manager($_SESSION['user_id'])) {
    $head = "<h2>部门其它未完成工作</h2>";
  	$where = " progress < 100 and creator_user_id in (select id from user_info where department_id = ".$_SESSION['department_id'].") ";
  	$where .= "and creator_user_id != ".$_SESSION['user_id']." and assignto != ".$_SESSION['user_id']." ";
  	return $head.gen_task_table($where, 0);
  }
}

$task_modify_form="";

$new_task_id = perform_insert_post('new_task_submit', 'task_info', $task_insert_fields);
if ($new_task_id > 0 && $_POST['mailassignment'] == 1) {
    $subject = "【qlog邮件通知】新增任务：".$_POST['title'];
    $message = "重要等级：".$_POST['priority']."\n";
    $message .= "是否出差：".($_POST['is_trip_out'] == 1 ? "是" : "否")."\n";
    $message .= "起止时间：".$_POST['scheduled_start_time']." ~ ".$_POST['deadline']."\n";
    $message .= "任务内容：\n".$_POST['content'];
    $from_user_id = $user_id;
    $to_user_id = $_POST['assignto'];

    send_mail($subject, $message, $from_user_id, $to_user_id);
}
$ret = perform_delete_post('delete_task_id', 'task_info');
if ($ret > 0) {
    // 待实现
}
$ret = perform_update_post('modify_task_submit', 'task_info', $task_modify_fields);
if ($ret > 0 && $_POST['mailassignment'] == 1) {
    $subject = "【qlog邮件通知】修改任务：".$_POST['title'];
    $message = "重要等级：".$_POST['priority']."\n";
    $message .= "是否出差：".($_POST['is_trip_out'] == 1 ? "是" : "否")."\n";
    $message .= "起止时间：".$_POST['scheduled_start_time']." ~ ".$_POST['deadline']."\n";
    $message .= "任务内容：\n".$_POST['content'];
    $from_user_id = $user_id;
    $to_user_id = $_POST['assignto'];

    send_mail($subject, $message, $from_user_id, $to_user_id);
}

$debug = 0;
$left_content = $task_form;
$right_content = gen_switch_divs(array("todo_list"=>get_todo_list().get_assigned_todo().get_department_todo(), "task_modify_form"=>$task_modify_form), "todo_list");

//echo $new_task_id < 0 ?
//     gen_twincol_page("Task", $left_content, $right_content, $debug) :
//	 gen_javascript_page("submit_a_value('new_log_task_id',$new_task_id, 'wlog.php')");

echo gen_twincol_page("Task", $left_content, $right_content, $debug);

?>